package com.thinksns.sociax.t4.android.popupwindow;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.android.widget.wheelview.AbstractWheelTextAdapter;
import com.thinksns.sociax.t4.android.widget.wheelview.OnWheelChangedListener;
import com.thinksns.sociax.t4.android.widget.wheelview.OnWheelScrollListener;
import com.thinksns.sociax.t4.android.widget.wheelview.WheelView;
import com.thinksns.sociax.t4.util.LogUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by zhiyicx on 2017/5/4.
 */

public class EventPickTimePopWindow implements OnWheelChangedListener, OnWheelScrollListener {
    private List<String> days;
    private List<String> hours;
    private List<String> minutes;

    private Activity activity;
    private PopupWindow popupWindow;
    private int animationStyle;
    private DismissListener dismissDialogListener;
    private TextView pick_pop_cancel_tv;
    private TextView pick_pop_confirm_tv;

    private WheelView pick_days_pop_wv;
    private WheelView pick_hours_pop_wv;
    private WheelView pick_minutes_pop_wv;

    private AddressTextAdapter daysWheelViewAdapter;
    private AddressTextAdapter hoursWheelViewAdapter;
    private AddressTextAdapter minutesWheelViewAdapter;

    private String sDays;
    private String sHours;
    private String sMinutes;

    private String returnTime = "";

    private String[] weeeks = {"周日","周一","周二","周三","周四","周五","周六"};

    public EventPickTimePopWindow(Activity activity,List<String> days,List<String> hours,List<String> minutes,
                                  int animationStyle, int width, int height){
        this.activity = activity;
        this.animationStyle = animationStyle;
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
        initPop(width,height);
    }

    private void initPop(int width,int heigh){
        View view = LayoutInflater.from(activity).inflate(R.layout.event_pick_time_pop_layout,null);
        pick_pop_cancel_tv = (TextView) view.findViewById(R.id.pick_pop_cancel_tv);
        pick_pop_confirm_tv = (TextView) view.findViewById(R.id.pick_pop_confirm_tv);

        pick_days_pop_wv = (WheelView) view.findViewById(R.id.pick_days_pop_wv);
        pick_hours_pop_wv = (WheelView) view.findViewById(R.id.pick_hours_pop_wv);
        pick_minutes_pop_wv = (WheelView) view.findViewById(R.id.pick_minutes_pop_wv);

        pick_hours_pop_wv.setCyclic(true);
        pick_minutes_pop_wv.setCyclic(true);

        popupWindow = new PopupWindow(view,width,heigh);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        // 设置popwindow如果点击外面区域，便关闭。
        popupWindow.setOutsideTouchable(true);
        if (animationStyle != 0) {
            popupWindow.setAnimationStyle(animationStyle);
        }

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setWindowNormal();
                if (dismissDialogListener != null) {
                    dismissDialogListener.onDismiss(returnTime);
                }
            }
        });
        pick_pop_confirm_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                returnTime = changeToTime();
                popupWindow.dismiss();
            }
        });
        pick_pop_cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                returnTime = "";
                popupWindow.dismiss();
            }
        });
    }

    private void initWheelView(){
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        calendar.setTime(date);

        sHours = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
        if(sHours.length() == 1){
            sHours = "0" + sHours;
        }

        sMinutes = String.valueOf(calendar.get(Calendar.MINUTE));
        if(sMinutes.length() == 1){
            sMinutes = "0" + sMinutes;
        }

        sDays = calendar.get(Calendar.YEAR) + "年"
                + (calendar.get(Calendar.MONTH) + 1) + "月"
                + calendar.get(Calendar.DAY_OF_MONTH) + "日 "
                + weeeks[calendar.get(Calendar.DAY_OF_WEEK)-1];
        LogUtils.logE(sHours + " " + sMinutes + " " + sDays);

        daysWheelViewAdapter = new AddressTextAdapter(activity, days, setDefaultItem(sDays,days) , 24, 18);
        hoursWheelViewAdapter = new AddressTextAdapter(activity, hours, setDefaultItem(sHours,hours) , 24, 18);
        minutesWheelViewAdapter = new AddressTextAdapter(activity, minutes, setDefaultItem(sMinutes,minutes) , 24, 18);

        pick_days_pop_wv.setViewAdapter(daysWheelViewAdapter);
        pick_days_pop_wv.setVisibleItems(5);
        pick_days_pop_wv.setCurrentItem(setDefaultItem(sDays,days));
        pick_days_pop_wv.addChangingListener(this);
        pick_days_pop_wv.addScrollingListener(this);

        pick_hours_pop_wv.setViewAdapter(hoursWheelViewAdapter);
        pick_hours_pop_wv.setVisibleItems(5);
        pick_hours_pop_wv.setCurrentItem(setDefaultItem(sHours,hours));
        pick_hours_pop_wv.addChangingListener(this);
        pick_hours_pop_wv.addScrollingListener(this);

        pick_minutes_pop_wv.setViewAdapter(minutesWheelViewAdapter);
        pick_minutes_pop_wv.setVisibleItems(5);
        pick_minutes_pop_wv.setCurrentItem(setDefaultItem(sMinutes,minutes));
        pick_minutes_pop_wv.addChangingListener(this);
        pick_minutes_pop_wv.addScrollingListener(this);

        sDays = (String) daysWheelViewAdapter.getItemText(pick_days_pop_wv.getCurrentItem());
        sHours = (String) hoursWheelViewAdapter.getItemText(pick_hours_pop_wv.getCurrentItem());
        sMinutes = (String) minutesWheelViewAdapter.getItemText(pick_minutes_pop_wv.getCurrentItem());

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        String currentText;
        switch (wheel.getId()){
            case R.id.pick_days_pop_wv:
                currentText = (String) daysWheelViewAdapter.getItemText(newValue);
                sDays = currentText;
                LogUtils.logE(sDays);
                setTextviewSize(currentText,daysWheelViewAdapter);
                break;
            case R.id.pick_hours_pop_wv:
                currentText = (String) hoursWheelViewAdapter.getItemText(newValue);
                sHours = currentText;
                LogUtils.logE(sHours);
                setTextviewSize(currentText,hoursWheelViewAdapter);
                break;
            case R.id.pick_minutes_pop_wv:
                currentText = (String) minutesWheelViewAdapter.getItemText(newValue);
                sMinutes = currentText;
                LogUtils.logE(sMinutes);
                setTextviewSize(currentText,minutesWheelViewAdapter);
                break;
        }
    }

    @Override
    public void onScrollingStarted(WheelView wheel) {
        LogUtils.logE("onScrollingStarted");
    }

    @Override
    public void onScrollingFinished(WheelView wheel) {

    }
    public void setTextviewSize(String curriteItemText, AbstractWheelTextAdapter adapter) {
        ArrayList<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textvew = (TextView) arrayList.get(i);
            currentText = textvew.getText().toString();
            if (curriteItemText.equals(currentText)) {
                LogUtils.logE("setTextviewSize 24" + curriteItemText + "  " +currentText);
                textvew.setTextSize(24);
                textvew.setTextColor(0xff333333);
            } else {
                LogUtils.logE("setTextviewSize 18 " + curriteItemText + "  " +currentText);
                textvew.setTextColor(0xffb3b3b3);
                textvew.setTextSize(18);
            }
        }
    }

    private int setDefaultItem(String item,List<String> datas){
        if(item.equals("")) {
            return 0;
        }
        for(int i =0; i < datas.size();i++){
            if(item.equals(datas.get(i))){
                return i;
            }
        }
        return 0;
    }

    public interface DismissListener{
        void onDismiss(String time);
    }

    public void setDismissDialogListener(DismissListener dismissDialogListener){
        this.dismissDialogListener = dismissDialogListener;
    }

    public void setAnimationStyle(int animationStyle){
        this.animationStyle = animationStyle;
    }

    /**
     * 设置窗口正常:有些界面不能够这样使用窗口直接透明化的方法，来设置popwindow的方法，但毕竟是少数，在子类中重写该方法返回null
     */
    protected void setWindowNormal() {
        setWindowAlpha(1.0f);
    }

    /**
     * 设置屏幕的透明度
     *
     * @param alpha 需要设置透明度
     */
    private void setWindowAlpha(float alpha) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = alpha;
        params.verticalMargin = 100;
        activity.getWindow().setAttributes(params);
    }

    /**
     * 显示popWindow :整个界面中的位置
     */

    public void showPopAtLocation(View parent, int offX, int offY, int gravity) {
        setWindowAlpha();
        // 设置popwindow显示位置
        popupWindow.showAtLocation(parent, gravity, offX, offY);
        if (Build.VERSION.SDK_INT != 24)
            popupWindow.update();
        //startAnim();
    }

    /**
     * 显示popWindow :相对于控件
     */
    @TargetApi(19)
    public void showPopAsDropDown(View parent, int offX, int offY, int gravity) {
        setWindowAlpha();
        // 设置popwindow显示位置
        try {
            popupWindow.showAsDropDown(parent, offX, offY, gravity);
        }catch (Throwable t){
            popupWindow.showAsDropDown(parent, offX, offY);
        }
        if (Build.VERSION.SDK_INT != 24)
            popupWindow.update();
        //startAnim();
    }

    /**
     * 显示popWindow,在屏幕的最下方
     */
    public void showPopAtDown(View parent) {
        setWindowAlpha();
        // 设置popwindow显示位置
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        if (Build.VERSION.SDK_INT != 24)
            popupWindow.update();
        initWheelView();
    }

    protected void setWindowAlpha() {
        setWindowAlpha(0.8f);
    }

    private class AddressTextAdapter extends AbstractWheelTextAdapter {
        List<String> list;

        protected AddressTextAdapter(Context context, List<String> list, int currentItem,
                                     int maxsize, int minsize) {
            super(context, R.layout.item_event_category, R.id.item_address, currentItem, maxsize, minsize);
            this.list = list;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }

    private String changeToTime(){
        String time;
        StringBuffer stringBufferDay = new StringBuffer(sDays);
        switch (stringBufferDay.length()){
            case 12:
                stringBufferDay.setCharAt(4,'-');
                stringBufferDay.setCharAt(6,'-');
                stringBufferDay.delete(8,12);
                stringBufferDay.insert(5,'0');
                stringBufferDay.insert(8,'0');
                break;
            case 13:
                stringBufferDay.setCharAt(4,'-');
                stringBufferDay.setCharAt(6,'-');
                stringBufferDay.delete(9,13);
                stringBufferDay.insert(5,'0');
                break;
            case 14:
                stringBufferDay.setCharAt(4,'-');
                stringBufferDay.setCharAt(7,'-');
                stringBufferDay.delete(10,14);
                break;
        }
        time = stringBufferDay.toString() + " " + sHours + ":" + sMinutes;
        LogUtils.logE(time);
        return time;
    }

}
